<?php
/**
 * 联系人管理类
 * 
 * @author  sunguide 
 * @version 1.0
 * @package main
 * @time 2013-9-24 11:39:08
 */

class ContactsAction extends Action {
	private $_uid = '';
	public function _initialize(){
		$this->_uid = session('uid');
		if(!$this->_uid) $this->display("Public:login");//(503,"对不起，您登录超时了，请重新登录！",1);
		//B('Authenticate', $action);
	}
	public function index(){}
	/**
	 * 手动添加联系人
	 * @param   type    uid ,array()
	 * @return  type    ajax
	 * @access  public 
	 * @static 
	 */
	public function addContact(){
		//查询分组给添加联系人用
		$ContactsGroup = M('ContactsCategory');
		C('TOKEN_ON',false);//动态关闭表单令牌
		$name = trim($_POST['name']);
		$uid = $this->_uid;
		if(!$name){
			$result = $this->childInParent($uid,0);
			$this->assign('category',$result);
			
			$this->display();
		}else{
			// 实例化Contacts模型
			$Contacts = M('Contacts');
			// 根据表单提交的POST数据创建数据对象
			$v = $Contacts->create();
			// 把创建的数据对象写入数据库
			if($v){
				$Contacts->create_time = datetime();
				$Contacts->update_time = datetime();
				$Contacts->owner_uid = $uid;
				$vo = $Contacts->add();	
				if($vo){
					$this->ajaxReturn(1,"添加联系人成功！",1);
				}else{
					$this->ajaxReturn(0,'添加联系人失败！',0);
				}
			}else{
				$this->ajaxReturn(0,'数据有误',0);
			}			
		}
	}
	/**
	 * 编辑修改联系人
	 * @param   type    uid ,param
	 * @return  type    ajax
	 * @access  public 
	 * @static 
	 */
	public function editContact(){
		$Contacts = M('Contacts');
		$ContactsGroup = M('ContactsGroup');
		$param = $this->_param();
		$uid = $this->_uid;
		$contacter_id = intval($param['contacter_id']);
		$v = $Contacts->where("owner_uid = $uid AND contacter_id = $contacter_id")->find();
		$ContactsGroup->where("owner_uid = $uid")->select();
		//dump($v);
		$this->assign('list',$v);
		
		$this->display();
	}	
	/**
	 * 提交编辑修改过的联系人
	 * @param   type    uid ,param
	 * @return  type    ajax
	 * @access  public 
	 * @static 
	 */
	public function editContactSubmit(){
		C('TOKEN_ON',false);//动态关闭表单令牌
		$param = $this->_param();
		$uid = $this->_uid;
		if($param['contacter_id']){
			$Contacts = M('Contacts');
			$data = array();
			$matchEn = array('name','mobile','identification_card','birthday','gender','company','comtel','comfax','comdepartment','job','comemail','comwebsite','comzip','comaddress','nickname','privateqq','privateemail','privatezip','privatewebsite','address');  
			foreach($matchEn as $v){
				if($param[$v]) $data[$v] = $param[$v];	
			}
			
			if(!empty($data)){
				$data['update_time'] = datetime();
				$data['owner_uid'] = $uid;
				$vo = $Contacts->where("contacter_id = {$param['contacter_id']}")->save($data);
				$error = $Contacts->getLastSql();
				if($vo){
					$this->ajaxReturn(1,"添加联系人成功！",1);
				}else{
					$this->ajaxReturn(0,'添加联系人失败'.$error,0);
				}
			}else{
				$this->ajaxReturn(0,'数据有误',0);
			}			
		}
	} // end func
	
	/**
	 * 删除联系人
	 * @param   type    uid ,param['contacter_id']
	 * @return  type    ajax
	 * @access  public 
	 * @static 
	 */
	public function delContacter(){
	    $Contacts = M('Contacts');
		$param = $this->_param();
		$uid = $this->_uid;
		$ID = intval($param['contacter_id']);
		if($ID){
			$data = array(
				'is_deleted' => 1
			);
			if($Contacts->where("contacter_id = $ID AND owner_uid = $uid")->save($data)){
				$this->ajaxReturn(1,"删除成功",1);
			}else{
				$this->ajaxReturn(0,"删除失败",0);
			}
		}else{
			$this->ajaxReturn(2,"参数错误",0);
		}
	} // end func

	/**
	 * 查询我的所有联系人 同Index.Action中的方法
	 * @param   type    uid ,param['contacter_id']
	 * @return  type    ajax
	 * @access  public 
	 * @static 
	 */
	public function myContact(){
		//查询分组给添加联系人用
		$ContactsGroup = M('ContactsGroup');
		$Contacts = M('Contacts');
		$get = $this->_param();
		
		if(!empty($get)){
			$where = ' a.is_deleted = 0 ';
			//$get['name']=trim($get['name']);
			//$get['mobile']=trim($get['mobile']);
			//if($get['name']) $where .= " AND name = '".$get['name']."'";
			//if($get['mobile'])   $where .= " AND mobile  = '".$get['mobile']."'";
			$get['keywords']=trim($get['keywords']);
			$get['group_id']=trim($get['group_id']);
			
			if($get['keywords'])  $where .= " AND name like '%".$get['keywords']."%' OR mobile like '%".$get['keywords']."%'";
			if($get['group_id'])  $where .= " AND a.group_id = '".$get['group_id']."'";
		}else{
			$where = " a.is_deleted = 0 ";
		}
		import('ORG.Util.Page');// 导入分页类
		$uid = $this->_uid;
		$where .= " AND a.owner_uid = ".$uid;
		$group = $this->childInParent($uid,0);
			
		//查询通讯录
		$count      = $Contacts->alias('a')->where($where)->count();// 查询满足要求的总记录数
		$Page       = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$Model = new Model();
		$sql = "SELECT a.*,b.category_name,b.category_id FROM sms_contacts AS a
				LEFT JOIN sms_contacts_category AS b ON a.category_id = 
				b.category_id
				WHERE ".$where."
				ORDER BY a.update_time DESC
				LIMIT ".$Page->firstRow.",".$Page->listRows;
				//alert("warn",$sql);
		//echo $sql;
		$list = $Model->query($sql);
		foreach($list as $key => $value){
			//$m7 = substr($value['mobile'],0,7);
			//$list[$key]['mobile'] = $m7."****";
		}
		$this->assign('list',$list);
		$this->assign('group',$group);
		$this->assign('count',$count);
		
		$this->assign('page',$show);
		$this->display();
	}
/** 没用
	public function setCategory(){
		//查询分组给添加联系人用
		$ContactsCategory = M('ContactsCategory');
		$uid = $this->_uid;
		$data=array(
			'uid' => $uid,
		);
		$v = $ContactsCategory->where($data)->select();
		$this->assign('group',$v);
		$this->display();
	}
**/	
	/**
	 * 添加分组
	 * @param   type    uid ,category_id
	 * @return  type    ajax
	 * @access  public 
	 * @static 
	 */
	public function addGroup(){
		$get = $this->_param();
		$ContactsGroup = M('ContactsGroup');
		$uid = $this->_uid;
		if($get['group_name']){
			$data=array(
				'owner_uid' => $uid,
				'group_name' => trim($get['group_name']),
				'parent_id'	=> ($categoryID=trim($get['parent_id'])) ? $categoryID:0   //经典，处理输入的数据是否合法
			);
			if($ContactsGroup->where($data)->find()){
				$this->ajaxReturn(1,"您已存在此分组",1);
			}else{
				$v = $ContactsGroup->add($data);
				if($v){
					$this->ajaxReturn(1,"添加分组成功",1);
				}else{
					$this->ajaxReturn(0,"添加分组失败",0);
				}
			}
		}else{
			
			$result = $this->childInParent($uid,0);
		
			$this->assign('category',$result);
			$this->display();
		}
	
	}
	/** 
	*	递归查询子分组（经典代码）
	*   @param $uid,$parentID
	*   @return array
	*/
	protected function childInParent($uid,$parentID){
		$ContactsGroup = M('ContactsGroup');
		$where=array(
				'owner_uid' => $uid,
				'parent_id'	=> $parentID
		);
		$parent = $ContactsGroup->where($where)->select();
		if($parent){
			foreach($parent as $key=>$value){
				$parent[$key]['child'] = $this->childInParent($uid,$value['category_id']);
			}
		}
		return $parent;	
	}
	/**
	   暂时不用
	*  查询当前用户的联系人分类,如果传递category_id就查询此分类下的子分类
	*  params uid ,category_id
	*/
	public function getCategory(){
		$Contacts = D('Contacts');
		$param = $this->_param();//获取传递参数
		$uid = $this->_uid;
		if($param['category_id']) $cid = $param['category_id'];
		$v = $Contacts->getCategory($uid,$cid);
		$count=count($v);
		if($count){
			if($count) $v['count'] = $count;
			$this->ajaxReturn($v,"获取分类成功",1);
		}else{
			$this->ajaxReturn(0,"暂无子分类",0);
		}	
	}
	//联系人黑名单显示
	public function blacklist(){
		$Model = M();
		$param = $this->_param();
		//dump($param);
		$where = array();
		$uid = $this->_uid;
		$param['mobile'] ? $where['A.mobile'] = $param['mobile']:1;
		$param['startdate'] ? $where['A.create_time'][] = array('EGT',$param['startdate']):1;//注意区间查询一定要这样哦
		$param['enddate'] ? $where['A.create_time'][] = array('ELT',$param['enddate']):1;
		$where['A.owner_uid'] = $uid;
		
		import('ORG.Util.Page');// 导入分页类
		$count      = $Model->table('sms_blacklist A')->join('sms_account B ON A.owner_uid = B.uid')->where($where)->count();// 查询满足要求的总记录数
		$Page       = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		
		$results = $Model->table('sms_blacklist A')->join('sms_account B ON A.owner_uid = B.uid')->field('A.*,B.uid,B.account')->where($where)->order('A.id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		//echo $Model->getLastSql();//打印sql语句
	
		
		foreach($results as $key=>$v){
			if($v['mobiles']){
				$results[$key]['mobiles'] = substr($v['mobiles'],0,23)." 等";
			}
		}
		$this->assign('page',$show);
		$this->assign('list',$results);
		$this->display();
	}
	
	/**
	 * 移除黑名单
	 * @param   type   $uid,$param['id']
	 * @return  type    ajax
	 * @access  public
	 * @static 
	 */
	function removeBlacklist()
	{
	    $Blacklist = M('Blacklist');
		$uid = $this->_uid;
		$param = $this->_param();
		if($param['id']){
			$where=array(
				'owner_uid' => $uid,
				'id' => $param['id']
			);
			$v = $Blacklist->where($where)->delete();
			if($v){
				$this->ajaxReturn(1,"移除成功",1);
			}else{
				$this->ajaxReturn(0,"移除失败",0);
			}
		}else{
     		$this->ajaxRetrun(2,"参数错误",0);
		}
	} // end func
	/**
	 * 新增黑名单
	 * @param   type   $uid,$param['id']
	 * @return  type    ajax
	 * @access  public
	 * @static 
	 */
	function blacklistAdd()
	{
	    $Blacklist = M('Blacklist');
		$uid = $this->_uid;
		$param = $this->_param();
		if($param['submit'] != 1){
			$this->display();
		}else if($param['mobile']){
			$data=array(
				'owner_uid' => $uid,
				'mobile' => trim($param['mobile']),
				'name'  => trim($param['name']),
				'create_time'=> datetime(),
				'status' => 1
			);
			$v = $Blacklist->add($data);
			if($v){
				$this->ajaxReturn(1,"添加成功",1);
			}else{
				$this->ajaxReturn(0,"添加失败",0);
			}
		}else{
     		$this->ajaxReturn(2,"手机号码不能为空",0);
		}
	} // end func
	/**
	 * 导入联系人页面显示
	 * @param   type   $uid
	 * @return  type   display
	 * @access  public
	 * @static 
	 */
	public function importContact(){
		//查询分组给添加联系人用
		$Contacts = D('Contacts');
		$uid = $this->_uid;
		$v = $Contacts->getGroup($uid,0);
		if($v == null){
			$v[0][group_name] = "无分组";
		}
		$this->assign('group',$v);
		$this->display();
	
	}
	/**
	 * 导出联系人页面显示
	 * @param   type   $uid
	 * @return  type   display
	 * @access  public
	 * @static 
	 */
	public function exportContact(){
		//查询分组给添加联系人用
		$Contacts = D('Contacts');
		$uid = $this->_uid;
		$v = $Contacts->getGroup($uid,0);
		if($v == null){
			$v[0][group_name] = "无分组";
		}
		$this->assign('group',$v);
		$this->display();
	
	}
	
	
	/**
	 * 显示联系人列表供发短信时从联系人列表中选择
	 * @param   type    $uid
	 * @return  type    display
	 * @access  public 
	 * @static  
	 */
	public function selectContact()
	{
	    $Contacts = M('Contacts');
		$ContactsGroup = M('ContactsGroup');
		$uid = $this->_uid;
		$group = $ContactsGroup->where("owner_uid = $uid")->select();
		import('ORG.Util.Page');// 导入分页类
			
		//查询通讯录
		$where = "owner_uid = $uid AND group_id = {$group[0]['group_id']}";
		$count      = $Contacts->where($where)->count();// 查询满足要求的总记录数
		$Page       = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$results = $Contacts->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
		//echo "sdfsd";
		$this->assign('group',$group);
		$this->assign('list',$results);
		$this->assign('page',$show);
		$this->display();
	} // end func

	//调试参数测试
    public function test(){
		$get['parent_id']='';
		$data=array(
				'uid' => 1,
				'category_name' => trim($get['category_name']),
				'parent_id'	=> ($categoryName=trim($get['parent_id'])) ? $categoryName:"dfd"
			);
			dump($data);
		$input = "10101010101010101010";
		$input = str_split($input);
		dump($input);
    }
	//联系人EXCEL导出
	public function excelExport(){
		import("ORG.PHPExcel.PHPExcel");
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("十目科技");
		$objProps->setLastModifiedBy("十目科技");    
		$objProps->setTitle("十目科技通讯录");    
		$objProps->setSubject("十目科技通讯录");    
		$objProps->setDescription("十目科技通讯录");    
		$objProps->setKeywords("十目科技通讯录");    
		$objProps->setCategory("十目科技通讯录");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
	    $matchCn = array('姓名','手机','身份证号','生日','性别','公司名称','公司电话','公司传真','公司部门','公司职务','公司邮箱','公司网址','公司邮编','公司地址','昵称','私人QQ','私人邮箱','私人邮编','私人网址','家庭地址');
		$matchEn = array('name','mobile','identification_card','birthday','gender','company','comtel','comfax','comdepartment','job','comemail','comwebsite','comzip','comaddress','nickname','privateqq','privateemail','privatezip','privatewebsite','address');  
		$input = "11111111111111111111";
		$icount = strlen($input);
		
		
		
		$mcount = count($matchCn);
		$input = str_split($input);
		if($icount != $mcount){
			$error['msg'] = "参数出错";
			
		}else{
			$objActSheet->setTitle('Sheet1');
			$A = 'A';
			$k = 0;
			foreach($input as $idata){
				if($idata){
					$objActSheet->setCellValue($A.'1', $matchCn[$k]);
					$MC[] = $matchEn[$k];
					$A++;
				}
				$k++;
			}
			/**
			$objActSheet->setCellValue('A1', '姓名');
			$objActSheet->setCellValue('B1', '尊称');
			$objActSheet->setCellValue('C1', '部门');
			$objActSheet->setCellValue('D1', '职位');
			$objActSheet->setCellValue('E1', '电话');
			$objActSheet->setCellValue('F1', 'Email');
			$objActSheet->setCellValue('G1', '地址');
			$objActSheet->setCellValue('H1', '邮编');
			$objActSheet->setCellValue('I1', '备注');
			$objActSheet->setCellValue('J1', '所属客户');
			$objActSheet->setCellValue('K1', '负责人');
			$objActSheet->setCellValue('L1', '创建人');
			$objActSheet->setCellValue('M1', '创建时间');
			**/

			//$where['owner_role_id'] = array('in',implode(',', getSubRoleId()));
			$list = M('contacts')->where($where)->select();
			$i = 1;
			foreach ($list as $k => $v) {
				$i++;
				$owner = D('RoleView')->where('role.role_id = %d', $v['owner_role_id'])->find();
				$creator = D('RoleView')->where('role.role_id = %d', $v['creator_role_id'])->find();
				//整理数据输出
				$imc = 0;
				for($ik = 'A';$ik <= $A;$ik++){
					$name = $MC[$imc];
					$objActSheet->setCellValue($ik.$i, $v[$name]);
					$imc++;
				}
				/*
				$objActSheet->setCellValue('A'.$i, $v['name']);
				$objActSheet->setCellValue('B'.$i, $v['mobile']);
				$objActSheet->setCellValue('C'.$i, $v['email']);
				$objActSheet->setCellValue('D'.$i, $v['address']);
				$objActSheet->setCellValue('E'.$i, $v['company']);
				$objActSheet->setCellValue('F'.$i, $v['department']);
				$objActSheet->setCellValue('G'.$i, $v['description']);
				*/
				
			}
			/*输出一些其他信息
			$customer_id = M('rContactsCustomer')->where('contacts_id = %d', $v['contacts_id'])->getField('customer_id');
				$customer_name = M('customer')->where('customer_id = %d' ,$customer_id)->getField('name');
				$objActSheet->setCellValue('J'.$i, $customer_name);
				$objActSheet->setCellValue('K'.$i, $owner['user_name'] .'['.$owner['department_name'].'-'.$owner['role_name'].']');
				$objActSheet->setCellValue('L'.$i, $creator['user_name'].'['.$creator['department_name'].'-'.$creator['role_name'].']');
				$objActSheet->setCellValue('M'.$i, date("Y-m-d H:i:s", $v['create_time']));
			*/
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			header("Content-Type: application/vnd.ms-excel;");
			header("Content-Disposition:attachment;filename=sm_contacts_".date('Y-m-d',mktime()).".xls");
			header("Pragma:no-cache");
			header("Expires:0");
			$objWriter->save('php://output'); 
		
		}
		
	}
	//联系人EXCEL导入
	public function excelImport(){
		$m_contacts = M('Contacts');
		if (isset($_FILES['excel']['size']) && $_FILES['excel']['size'] != null) {
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 100000000 ;// 设置附件上传大小
			$upload->allowExts  = array('xls');// 设置附件上传类型
			$upload->savePath =  './Uploads/contacts/';// 设置附件上传目录
			$upload->saveRule = 'time';
			$upload->autoSub = true; //开启子目录保存
			$upload->subType = 'date';//子目录以日期格式保存
			$upload->dateFormat = 'Ym/d';//子目录日期模式下保存格式
			$upload->autoCheck = true;
			$dirname = './Uploads/contacts/';// . date('Ym', time()).'/'.date('d', time()).'/'
			if (!is_dir($dirname) && !mkdir($dirname, 0777, true)) {
				$error['msg'] = "附件上传目录不可写";
			}
			if(!$upload->upload()) {// 上传错误提示错误信息
			$this->error($upload->getErrorMsg());
			}else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();   //$info[0]['savename'];
			}	
			$filename = $info[0]['savename'];
		}
		
		if(is_array($info[0]) && !empty($info[0])){
			$savePath = $dirname . $info[0]['savename'];
		}else{
			$error['msg'] .= "上传失败";
		}
		import("ORG.PHPExcel.PHPExcel");
		$PHPExcel = new PHPExcel();
		$PHPReader = new PHPExcel_Reader_Excel2007();
		if(!$PHPReader->canRead($savePath)){
			$PHPReader = new PHPExcel_Reader_Excel5();
		}
		$PHPExcel = $PHPReader->load($savePath);
		$currentSheet = $PHPExcel->getSheet(0);
		$currentSheet->getStyle()->getFont()->applyFromArray(
	 		array(
	 			'name'	  => 'Arial'
	 			)
	 	);
	    
		$allRow = $currentSheet->getHighestRow();
		
		$matchCn = array('姓名','手机','身份证号','生日','性别','公司名称','公司电话','公司传真','公司部门','公司职务','公司邮箱','公司网址','公司邮编','公司地址','昵称','私人QQ','私人邮箱','私人邮编','私人网址','家庭地址');
		$matchEn = array('name','mobile','identification_card','birthday','gender','company','comtel','comfax','comdepartment','job','comemail','comwebsite','comzip','comaddress','nickname','privateqq','privateemail','privatezip','privatewebsite','address');
	//--------------------------------------
	//整理要导入的具体项目
		$flag = 1;
		$AZ = 'A';
		$MT = array();
		$error['msg'] .= "以下格式不对:";
		while($flag){
			
			$value = $currentSheet->getCell($AZ.'1')->getValue();
			if($value == '') {
				$flag = 0;
				break;
			}
		
			echo $value;
			$k = 0;
			$is = false;
			foreach($matchCn as $m){
				if($value == $m){
					$iflag = $flag - 1;
					
					$MT[] = array(
						'position' => $AZ,
						'en'       => $matchEn[$k]
					);
					$is = true;
					echo $matchEn[$k];
					break;
				}
				$k++;
			}
			if(!$is){
				$error = $error.$value."--";
			}
			$AZ++;
			$flag++;	
		}
//--------------------------------------
		for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
			$data = array();
			$data['uid'] = session('uid');
			$data['create_time'] = date('Y-m-d H:i:s');
			$data['update_time'] = date('Y-m-d H:i:s');
			$data['owner_uid'] = trim($_POST['owner_role_id']);
//------------------------------------------
foreach($MT as $mt){
	$currentSheet->getStyle($mt['position'].$currentRow)->getFont()->applyFromArray(array('name' => 'Arial'));
	//dump($currentSheet->getStyle($mt['position'].$currentRow)->getFont());
	//echo $mt['position'].$currentRow;
	$objStyleAZ = $currentSheet->getStyle($mt['position'].$currentRow);  
  
	//设置单元格内容的数字格式。  
	//  
	//如果使用了 PHPExcel_Writer_Excel5 来生成内容的话，  
	//这里需要注意，在 PHPExcel_Style_NumberFormat 类的 const 变量定义的  
	//各种自定义格式化方式中，其它类型都可以正常使用，但当setFormatCode  
	//为 FORMAT_NUMBER 的时候，实际出来的效果被没有把格式设置为"0"。需要  
	//修改 PHPExcel_Writer_Excel5_Format 类源代码中的 getXf($style) 方法，  
	//在 if ($this->_BIFF_version == 0x0500) { （第363行附近）前面增加一  
	//行代码:   
	//if($ifmt === '0') $ifmt = 1;  
	//  
	//设置格式为PHPExcel_Style_NumberFormat::FORMAT_NUMBER，避免某些大数字  
	//被使用科学记数方式显示，配合下面的 setAutoSize 方法可以让每一行的内容  
	//都按原始内容全部显示出来。  
	$objStyleAZ->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);    
	//设置字体  
	$objFontA5 = $objStyleAZ->getFont();  
	$objFontA5->setName('新宋体');  
	$cv = $currentSheet->getCell($mt['position'].$currentRow)->getValue();
	$var = $mt['en'];
	$cv != '' && $cv != null ? $data[$var]= $cv : ''; ; 
}
//------------------------------------------
/*			$name = $currentSheet->getCell('A'.$currentRow)->getValue();
			$name != '' && $name != null ? 
			$mobile = $currentSheet->getCell('B'.$currentRow)->getValue();
			$mobile != '' && $mobile != null ? $data['mobile'] = $mobile : '';
			$gender = $currentSheet->getCell('C'.$currentRow)->getValue();
			$gender != '' && $gender != null ? $data['gender'] = $gender : '';
			$email = $currentSheet->getCell('D'.$currentRow)->getValue();
			$email != '' && $email != null ? $data['email'] = $email : '';
			$address = $currentSheet->getCell('E'.$currentRow)->getValue();
			$address != '' && $address != null ? $data['address'] = $address : '';
			$company = $currentSheet->getCell('F'.$currentRow)->getValue();
			$company != '' && $company != null ? $data['company'] = $company : '';				
			$department = $currentSheet->getCell('G'.$currentRow)->getValue();
			$department != '' && $department != null ? $data['department'] = $department : '';
			$description = $currentSheet->getCell('H'.$currentRow)->getValue();
			$description != '' && $description != null ? $data['description'] = $description : '';
			dump($data);

		*/
			if(!$m_contacts->add($data)) {
				alert('error', '导入至第' . $currentRow . '行出错', U('leads/index'));
				$error['msg'] .= '导入至第' . $currentRow . '行出错';
				break;
			}
		
			
		} 
	}
	//联系人Txt导出
	public function exportContactsTxt(){
		import("ORG.PHPExcel.PHPExcel");
		$uid = $this->_uid;
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("十目科技");
		$objProps->setLastModifiedBy("十目科技");    
		$objProps->setTitle("十目科技通讯录");    
		$objProps->setSubject("十目科技通讯录");    
		$objProps->setDescription("十目科技通讯录");    
		$objProps->setKeywords("十目科技通讯录");    
		$objProps->setCategory("十目科技通讯录");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
	    $matchCn = array('姓名','手机','身份证号','生日','性别','公司名称','公司电话','公司传真','公司部门','公司职务','公司邮箱','公司网址','公司邮编','公司地址','昵称','私人QQ','私人邮箱','私人邮编','私人网址','家庭地址');
		$matchEn = array('name','mobile','identification_card','birthday','gender','company','comtel','comfax','comdepartment','job','comemail','comwebsite','comzip','comaddress','nickname','privateqq','privateemail','privatezip','privatewebsite','address');  
		$param = $this->_param();
		$input = trim($param['select']);
		if($input){
		
		}else{
			$input = "11111111111000000000";
		}
		$groupID = intval($param['group_id']);

		if(trim($param['exportFileName'])) $fileName = trim($param['exportFileName']);
		else $fileName = 'sm_contacts_'.date('Y-m-d');
		$icount = strlen($input);
		
		
		
		$mcount = count($matchCn);
		$input = str_split($input);
		if($icount != $mcount){
			$error['msg'] = "参数出错";
			
		}else{
			$objActSheet->setTitle('Sheet1');
			$A = 'A';
			$k = 0;
			foreach($input as $idata){
				if($idata){
					$objActSheet->setCellValue($A.'1', $matchCn[$k]);
					$MC[] = $matchEn[$k];
					$A++;
				}
				$k++;
			}
			/**
			$objActSheet->setCellValue('A1', '姓名');
			$objActSheet->setCellValue('B1', '尊称');
			$objActSheet->setCellValue('C1', '部门');
			$objActSheet->setCellValue('D1', '职位');
			$objActSheet->setCellValue('E1', '电话');
			$objActSheet->setCellValue('F1', 'Email');
			$objActSheet->setCellValue('G1', '地址');
			$objActSheet->setCellValue('H1', '邮编');
			$objActSheet->setCellValue('I1', '备注');
			$objActSheet->setCellValue('J1', '所属客户');
			$objActSheet->setCellValue('K1', '负责人');
			$objActSheet->setCellValue('L1', '创建人');
			$objActSheet->setCellValue('M1', '创建时间');
			**/

			$where['group_id'] = $groupID; //array('in',implode(',', getSubRoleId()));
			$where['owner_uid'] = $uid;
			$list = M('contacts')->where($where)->select();
			//dump($list);
			$i = 1;
			foreach ($list as $k => $v) {
				$i++;
				//$owner = D('RoleView')->where('role.role_id = %d', $v['owner_role_id'])->find();
				//$creator = D('RoleView')->where('role.role_id = %d', $v['creator_role_id'])->find();
				//整理数据输出
				$imc = 0;
				for($ik = 'A';$ik <= $A;$ik++){
					$name = $MC[$imc];
					$objActSheet->setCellValue($ik.$i, $v[$name]);
					$imc++;
				}
				/*
				$objActSheet->setCellValue('A'.$i, $v['name']);
				$objActSheet->setCellValue('B'.$i, $v['mobile']);
				$objActSheet->setCellValue('C'.$i, $v['email']);
				$objActSheet->setCellValue('D'.$i, $v['address']);
				$objActSheet->setCellValue('E'.$i, $v['company']);
				$objActSheet->setCellValue('F'.$i, $v['department']);
				$objActSheet->setCellValue('G'.$i, $v['description']);
				*/
				
			}
			/*输出一些其他信息
			$customer_id = M('rContactsCustomer')->where('contacts_id = %d', $v['contacts_id'])->getField('customer_id');
				$customer_name = M('customer')->where('customer_id = %d' ,$customer_id)->getField('name');
				$objActSheet->setCellValue('J'.$i, $customer_name);
				$objActSheet->setCellValue('K'.$i, $owner['user_name'] .'['.$owner['department_name'].'-'.$owner['role_name'].']');
				$objActSheet->setCellValue('L'.$i, $creator['user_name'].'['.$creator['department_name'].'-'.$creator['role_name'].']');
				$objActSheet->setCellValue('M'.$i, date("Y-m-d H:i:s", $v['create_time']));
			*/
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			header("Content-Type: application/vnd.ms-excel;");
			header("Content-Disposition:attachment;filename=".$fileName.".xls");
			header("Pragma:no-cache");
			header("Expires:0");
			$objWriter->save('php://output'); 
		
		}
		//dump($error);
	}
	//方法备份，弃用
	public function exportContactsTxtbak(){
		import("ORG.PHPExcel.PHPExcel");
		$uid = $this->_uid;
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("十目科技");
		$objProps->setLastModifiedBy("十目科技");    
		$objProps->setTitle("十目科技通讯录");    
		$objProps->setSubject("十目科技通讯录");    
		$objProps->setDescription("十目科技通讯录");    
		$objProps->setKeywords("十目科技通讯录");    
		$objProps->setCategory("十目科技通讯录");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
	    $matchCn = array('姓名','手机','身份证号','生日','性别','公司名称','公司电话','公司传真','公司部门','公司职务','公司邮箱','公司网址','公司邮编','公司地址','昵称','私人QQ','私人邮箱','私人邮编','私人网址','家庭地址');
		$matchEn = array('name','mobile','identification_card','birthday','gender','company','comtel','comfax','comdepartment','job','comemail','comwebsite','comzip','comaddress','nickname','privateqq','privateemail','privatezip','privatewebsite','address');  
		$param = $this->_param();
		$input = trim($param['select']);
		$groupID = intval($param['group_id']);
		$icount = strlen($input);
		
		
		
		$mcount = count($matchCn);
		$input = str_split($input);
		if($icount != $mcount){
			$error['msg'] = "参数出错";
			
		}else{
			$objActSheet->setTitle('Sheet1');
			$A = 'A';
			$k = 0;
			foreach($input as $idata){
				if($idata){
					$objActSheet->setCellValue($A.'1', $matchCn[$k]);
					$MC[] = $matchEn[$k];
					$A++;
				}
				$k++;
			}
			/**
			$objActSheet->setCellValue('A1', '姓名');
			$objActSheet->setCellValue('B1', '尊称');
			$objActSheet->setCellValue('C1', '部门');
			$objActSheet->setCellValue('D1', '职位');
			$objActSheet->setCellValue('E1', '电话');
			$objActSheet->setCellValue('F1', 'Email');
			$objActSheet->setCellValue('G1', '地址');
			$objActSheet->setCellValue('H1', '邮编');
			$objActSheet->setCellValue('I1', '备注');
			$objActSheet->setCellValue('J1', '所属客户');
			$objActSheet->setCellValue('K1', '负责人');
			$objActSheet->setCellValue('L1', '创建人');
			$objActSheet->setCellValue('M1', '创建时间');
			**/

			$where['group_id'] = $groupID; //array('in',implode(',', getSubRoleId()));
			$where['owner_uid'] = $uid;
			$list = M('contacts')->where($where)->select();
			$i = 1;
			foreach ($list as $k => $v) {
				$i++;
				//$owner = D('RoleView')->where('role.role_id = %d', $v['owner_role_id'])->find();
				//$creator = D('RoleView')->where('role.role_id = %d', $v['creator_role_id'])->find();
				//整理数据输出
				$imc = 0;
				for($ik = 'A';$ik <= $A;$ik++){
					$name = $MC[$imc];
					$objActSheet->setCellValue($ik.$i, $v[$name]);
					$imc++;
				}
				/*
				$objActSheet->setCellValue('A'.$i, $v['name']);
				$objActSheet->setCellValue('B'.$i, $v['mobile']);
				$objActSheet->setCellValue('C'.$i, $v['email']);
				$objActSheet->setCellValue('D'.$i, $v['address']);
				$objActSheet->setCellValue('E'.$i, $v['company']);
				$objActSheet->setCellValue('F'.$i, $v['department']);
				$objActSheet->setCellValue('G'.$i, $v['description']);
				*/
				
			}
			/*输出一些其他信息
			$customer_id = M('rContactsCustomer')->where('contacts_id = %d', $v['contacts_id'])->getField('customer_id');
				$customer_name = M('customer')->where('customer_id = %d' ,$customer_id)->getField('name');
				$objActSheet->setCellValue('J'.$i, $customer_name);
				$objActSheet->setCellValue('K'.$i, $owner['user_name'] .'['.$owner['department_name'].'-'.$owner['role_name'].']');
				$objActSheet->setCellValue('L'.$i, $creator['user_name'].'['.$creator['department_name'].'-'.$creator['role_name'].']');
				$objActSheet->setCellValue('M'.$i, date("Y-m-d H:i:s", $v['create_time']));
			*/
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			header("Content-Type: application/vnd.ms-excel;");
			header("Content-Disposition:attachment;filename=sm_contacts_".date('Y-m-d',mktime()).".xls");
			header("Pragma:no-cache");
			header("Expires:0");
			$objWriter->save('php://output'); 
		
		}
		
	}
	//联系人Txt导入
	public function txtImport(){
		$Contacts = M('Contacts');
		$param = $this->_param('group_id');
		$groupID = $param;
		if (isset($_FILES['file']['size']) && $_FILES['file']['size'] != null) {
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 100000000 ;// 设置附件上传大小
			$upload->allowExts  = array('txt');// 设置附件上传类型
			$upload->savePath =  './Uploads/contacts/';// 设置附件上传目录
			$upload->saveRule = 'time';
			$upload->autoSub = true; //开启子目录保存
			$upload->subType = 'date';//子目录以日期格式保存
			$upload->dateFormat = 'Ym/d';//子目录日期模式下保存格式
			$upload->autoCheck = true;
			$dirname = './Uploads/contacts/';// . date('Ym', time()).'/'.date('d', time()).'/'
			if (!is_dir($dirname) && !mkdir($dirname, 0777, true)) {
				$error['msg'] = "附件上传目录不可写";
			}
			if(!$upload->upload()) {// 上传错误提示错误信息
			$this->error($upload->getErrorMsg());
			}else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();   //$info[0]['savename'];
			}	
			$filename = $info[0]['savename'];
		}else{
		
			$this->ajaxReturn(100,"上传的文件不存在",0);
		}
		
		if(is_array($info[0]) && !empty($info[0])){
			$savePath = $dirname . $info[0]['savename'];
		}else{
			$error['msg'] .= "上传失败";
		}
	    $matchCn = array('姓名','手机','身份证号','生日','性别','公司名称','公司电话','公司传真','公司部门','公司职务','公司邮箱','公司网址','公司邮编','公司地址','昵称','私人QQ','私人邮箱','私人邮编','私人网址','家庭地址');
		$matchEn = array('name','mobile','identification_card','birthday','gender','company','comtel','comfax','comdepartment','job','comemail','comwebsite','comzip','comaddress','nickname','privateqq','privateemail','privatezip','privatewebsite','address');  	
		$mcount = count($matchCn);
		$input = str_split($input);
//读取文件
		$file = $upload->savePath.$info[0]['savename'];//'words.txt';//10W条记录的TXT源文件
		$lines = file_get_contents($file);
		$lines = iconv('GB2312', 'UTF-8', $lines);//转换字符集
		//echo $lines;
		ini_set('memory_limit', '-1');//不要限制Mem大小，否则会报错
		$line=explode("\n",$lines);
		//dump($line);
		$all_count = count($line);//记录导入的数据的联系人数据量
		$all_count = $all_count?$all_count:0;
		
		
		//var_dump($line);
		//echo $line[0];
		$items = explode(",",$line[0]);
		//print_r($items);
		//echo $items[0];
		$match = array();
		$matchPostion = array();
		foreach($items as $key=>$is){
			$is = trim($is);
			//echo 'is'.$is;
			foreach($matchCn as $im => $mn){
				if($is == $mn){
					$match[] = $matchEn[$im];
					$matchPostion[] = $key;//记录对应的位置，方便查找数据
				}
			}
		}
		//dump($match);
		//dump($matchPostion);
		$result['success'] = 0;
		$result['fail'] = 0;
		$result['repeat'] = 0;
		$result['exist'] = 0;
		$result['count'] =$all_count - 1;
		for ($currentRow = 1;$currentRow < $all_count;$currentRow++) {
			$currentLine = explode(",",$line[$currentRow]);
			$data = array();
			foreach($match as $im => $v){
				$data[$v] = trim($currentLine[$im]);
			}
			$data['owner_uid'] = $this->_uid;
			$data['create_time'] = datetime();
			$data['update_time'] = datetime();
			if($groupID) $data['group_id'] = $groupID;
			//dump($data);
			if($data['name']) $isTrue = $Contacts->add($data);
			if($isTrue){
				$result['success']++;
			}else{
				$result['fail']++;
			}
		}	
		$this->ajaxReturn($result,"结果：导入成功{$result['success']}个，失败{$result['fail']}个,重复{$result['repeat']}个,已存在{$result['exist']}个",1);
	} 
}
